package com.yuan.mall1.service.impl;

import com.lly835.bestpay.config.WxPayConfig;
import com.lly835.bestpay.enums.BestPayPlatformEnum;
import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.enums.OrderStatusEnum;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.service.BestPayService;
import com.lly835.bestpay.service.impl.BestPayServiceImpl;
import com.yuan.mall1.dao.PayInfoMapper;
import com.yuan.mall1.enums.PayPlatformEnum;
import com.yuan.mall1.pojo.PayInfo;
import com.yuan.mall1.service.IPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * 这里的商户秘钥是错误的，只要使用真实的appid和mchid和mchKey就可以了。
 * 这里是把response得到的CodeUrl进行返回到了前台页面。
 */
@Slf4j
@Service
public class PayService implements IPayService {
    @Autowired
    private BestPayService bestPayService;
    @Resource
    private PayInfoMapper payInfoMapper;//@Autowired这个不影响，是IDEA的检测级别的原因
    @Override
    public PayResponse create(String orderId, BigDecimal amount,BestPayTypeEnum bestPayTypeEnum) {//订单号，金额
        //1.写入数据库
        PayInfo payinfo = new PayInfo(Long.parseLong(orderId),
                PayPlatformEnum.getPayPlatformEnum(bestPayTypeEnum).getCode(),
                OrderStatusEnum.NOTPAY.name(),
               amount);
        payInfoMapper.insertSelective(payinfo);
       /* if(bestPayTypeEnum != BestPayTypeEnum.WXPAY_NATIVE && bestPayTypeEnum != BestPayTypeEnum.ALIPAY_PC){
            throw new RuntimeException("暂不支持的支付类型");
        }*/
        //支付订单
        PayRequest request = new PayRequest();
        request.setOrderName("3533162-123345");
//        request.setOrderId("123456");
        request.setOrderId(orderId);
        request.setOrderAmount(amount.doubleValue());
        request.setPayTypeEnum(bestPayTypeEnum);

        PayResponse response = bestPayService.pay(request);
        log.info("发起支付 response={}",response);

        return response;
    }

    /**
     * 异步通知处理
     * @param notifyData
     */
    @Override
    public String asyncNotify(String notifyData) {
        //1.签名校验,如果要看实现内容，选中asyncNotify 然后Ctrl+alt+B选第二个方法，就可以看到具体实现方法细节
        PayResponse payResponse = bestPayService.asyncNotify(notifyData);
        log.info("异步通知 payResponse={}",payResponse);
        //2.金额校验（从数据库中查询订单）
        //比较严重（正常情况下不会发生的）发出警告：钉钉，短信报警
        PayInfo payInfo = payInfoMapper.selectByOrderNo(Long.parseLong(payResponse.getOrderId()));
        if(payInfo ==null){
            //告警
            throw new RuntimeException("通过orderNo查询到的结果是null");
        }
        //如果订单支付状态不是”已支付“
        if(!payInfo.getPlatformStatus().equals(OrderStatusEnum.SUCCESS.name())){
            //支付金额和数据库中的金额进行比对不相等是报警
            if(payInfo.getPayAmount().compareTo(BigDecimal.valueOf(payResponse.getOrderAmount()))!= 0){
                throw new RuntimeException("异步通知中的金额和数据库里的不一致，orderNo=" + payResponse.getOrderId());
            }
            //相等的情况
            //3.修改订单支付状态
            payInfo.setPlatformStatus(OrderStatusEnum.SUCCESS.name());
            payInfo.setPlatformNumber(payResponse.getOutTradeNo());//交易流水号，由平台产生，是一个票据
            payInfoMapper.updateByPrimaryKeySelective(payInfo);

        }
        //TODO pay发送MQ消息，mall接受MQ消息
        if(payResponse.getPayPlatformEnum()== BestPayPlatformEnum.WX){
            //4.告诉微信不要再通知
            return "<xml>\n" +
                    "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                    "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                    "</xml>";
        }else if(payResponse.getPayPlatformEnum()==BestPayPlatformEnum.ALIPAY){
            return "success";
        }

        throw new RuntimeException("异步通知中错误的支付平台");
    }

    @Override
    public PayInfo queryByOrderId(String orderId){
        return payInfoMapper.selectByOrderNo(Long.parseLong(orderId));
    }
}
/**
 * http://localhost:8080/pay/create?orderId=1234567891234&amount=0.01&payType=WXPAY_NATIVE
 *
 */


